package com.fe.class01;


import java.util.Arrays;

/**
 * @Description 在一个有序数组中，找某个数是否存在
 * @Author sosuke :-)
 * @Date 2021/11/30 22:49
 */
public class Code04_BSExist {

    /**
     * 使用二分法查找某数
     *
     * @param sortedArr
     * @param num
     * @return
     */
    public static boolean exist(int[] sortedArr, int num) {
        if (null == sortedArr || sortedArr.length == 0) return false;
        int L = 0;
        int R = sortedArr.length - 1;
        int mid = 0;
        // L..R 至少两个数的时候
        while (L < R) {
            mid = L + ((R - L) >> 1); // 防止溢出
            if (sortedArr[mid] == num) {
                return true;
            } else if (sortedArr[mid] > num) {
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return sortedArr[L] == num;
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 10;
        int maxValue = 100;

        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int num = (int) (Math.random() * (maxValue + 1) - Math.random() * (maxValue));
            boolean res1 = testExist(arr, num);
            boolean res2 = exist(arr, num);
            if (res1 != res2) {
                succeed = false;
                System.out.println(Arrays.toString(arr));
                System.out.println("the num is " + num);
                System.out.println("res1 = " + res1 + ", res2 = " + res2);
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");

        int[] arr = generateRandomArray(maxSize, maxValue);
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        int num = (int) (Math.random() * (maxValue + 1) - Math.random() * (maxValue));
        System.out.println("find num = " + num);
        System.out.println(exist(arr, num));
    }

    private static boolean testExist(int[] arr, int num) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == num) {
                return true;
            }
        }
        return false;
    }

    private static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) (Math.random() * (maxSize + 1))];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * (maxValue + 1) - Math.random() * (maxValue));
        }
        return arr;
    }

}
